package org.gitos.cloud.cmd.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gitos.cloud.domain.annotation.UnAuth;
import org.gitos.cloud.domain.comm.BConstant;
import org.gitos.cloud.domain.exception.NotificationException;
import org.gitos.cloud.util.ContextKit;
import org.gitos.cloud.util.JSession;
import org.gitos.cloud.util.RedisHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Optional;

/**
 * Created by shizhengchu on 16/4/10.
 */
@Component
public class BAuthInterceptor implements HandlerInterceptor {

	private static final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);
	@Autowired
	StringRedisTemplate stringRedisTemplate;
	@Value("${session.expireTime}")
	private int interval;

	@Override
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
			throws Exception {
		if (o instanceof HandlerMethod) {
			Optional<JSession> op_jsession = ContextKit.getJSession(httpServletRequest);
			if (op_jsession.isPresent() == false || op_jsession.get().isInvalidate()) {
				op_jsession = Optional.of(new JSession());
			}
			JSession jsession = op_jsession.get();
			jsession.setMaxInactiveInterval(interval);
			httpServletRequest.setAttribute(BConstant.JSESSION_ID_REQUEST, jsession.getGlobalSessionId());
			System.out.println("将session存入redis：" + JSONObject.toJSONString(jsession));
			RedisHelper.setWithDefaultExireTime(jsession.getGlobalSessionId(), jsession);
			UnAuth unAuth = ((HandlerMethod) o).getMethod().getAnnotation(UnAuth.class);
			if (unAuth == null) {
				String userJson = jsession.getData();
				if (StringUtils.isEmpty(userJson)) {
					httpServletResponse.sendRedirect("/background/loginWeb");
					return false;
				}
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object o, Exception e) throws Exception {
		Object jId = httpServletRequest.getAttribute(BConstant.JSESSION_ID_REQUEST);
		JSession jsession = null;
		if (jId == null) {
			jsession = new JSession();
		}
		String jsession_id = jId.toString();
		jsession = RedisHelper.getJSession(jsession_id);
		if (jsession == null) {
			jsession = new JSession();
		} else {
			// 设置最近访问时间
			jsession.setLastAccessedTime(System.currentTimeMillis());
			System.out.println("设置cookie和更新redis：【" + JSONObject.toJSONString(jsession));
			ContextKit.setCookieAuth(httpServletRequest, httpServletResponse, jsession);
		}
		if (e == null) {
			return;
		}
		if (e instanceof NotificationException) {
			log.info(e.getMessage());
			httpServletResponse.getWriter().write(
					"\"fail\":true,\"msg\":\"" + ((NotificationException) e).getMsg() + "\"");
		} else {
			log.info(e.getMessage());
			httpServletResponse.getWriter().write("\"fail\":true,\"msg\":\"发生未知错误\"");
		}
	}
}
